<template>
  <div class="box">
    <header>
      <div class="hello">
        <p>Hello!</p>
        <p>欢迎使用智农云平台</p>
      </div>
      <div class="logo" @click="history">
        <img src="./img/u50.svg" alt="">
        <img src="./img/u51.svg" alt="">
      </div>
    </header>
    <div class="content">
      <div class="menu">
        <ul>
          <li><span @click="flagList">一号棚 ▼</span>
            <ul class="menu_two" v-if="flag">
              <li>二号温棚</li>
              <li>三号温棚</li>
              <li>四号温棚</li>
              <li>五号温棚</li>
            </ul>
          </li>
        </ul>
        <div class="news" @click="caveat">
          <img src="./img/u35.svg" alt="">
        </div>
      </div>
      <div class="content_box">
        <ul>
          <li @click="() => { tmp(1) } ">
            <div>
              <span>温度</span>
              <img src="./img/u6.svg" alt="">
            </div>
            <p>{{ this.$store.state.data.tem }}°C</p>
            <p>Min:{{ this.$store.state.history.temMin }}°C</p>
            <p>MaX:{{ this.$store.state.history.temMax }}°C</p>
          </li>
          <li @click="() => { tmp(2) } ">
            <div>
              <span>湿度</span>
              <img src="./img/u6.svg" alt="">
            </div>
            <p>{{ this.$store.state.data.hum }}°C</p>
            <p>Min:{{ this.$store.state.history.humMin }}°C</p>
            <p>MaX:{{ this.$store.state.history.humMax }}°C</p>
          </li>
          <li @click="() => { tmp(3) } ">
            <div>
              <span>光照</span>
              <img src="./img/u6.svg" alt="">
            </div>
            <p>{{ this.$store.state.data.light }}LUX</p>
            <p>Min:{{ this.$store.state.history.lightMin }}°C</p>
            <p>MaX: {{ this.$store.state.history.lightMax }} °C</p>
          </li>
          <li @click="() => { tmp(4) } ">
            <div>
              <span>CO2</span>
              <img src="./img/u27.svg" alt="">
            </div>
            <p>28.22°C</p>
            <p>Min:24°C</p>
            <p>MaX:30°C</p>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>

export default {
  data () {
    return {
      flag: false,
      mqtt: ''
    }
  },
  mounted () {
var mqtt;
    var reconnectTimeout = 3000;	//连接超时时长
    var host = '49.232.150.163';    // hostname or IP address//MQTT服务器ip地址
    var port = 9001;					//MQTT代理器端口
    var topic = 'Temp';        // 定义订阅主题类型温度
    var topic1 = 'Hum';				// 定义订阅主题类型湿度
    var clientId = 'client-' + Math.ceil(Math.random() * 1000);
    var topic2 = 'Hv';				// 定义订阅主题类型光照强度
    var topic3 = 'Co2';						// 定义订阅主题类型CO2浓度
    var useTLS = false;
    var username = null;
    var password = null;
    //username = "test";
    //password = "123456";
    var cleansession = true;
    var addr = [];

    function MQTTconnect() {            //连接函数：连接到MQTT代理器
      mqtt = new Paho.MQTT.Client(host, port, clientId);
      var options = {
        invocationContext: {
          host: host,
          port: port,
          path: mqtt.path,
          clientId: clientId
        },
        timeout: 5,
        useSSL: useTLS,
        cleanSession: cleansession,
        onSuccess: onConnect,
        onFailure: function (message) {
          alert("connect failed..............");//调试语句连接代理器 失败打印
          // $('#status').val("Connection failed: " + message.errorMessage + "Retrying");
          setTimeout(MQTTconnect, reconnectTimeout);
        }
      };

      mqtt.onConnectionLost = onConnectionLost;
      mqtt.onMessageArrived = onMessageArrived;

      if (username != null) {
        options.userName = username;
        options.password = password;
      }
      mqtt.connect(options);
    }

    function onConnect() {		//连接代理器成功回调函数			
      // Connection succeeded; subscribe to our topic//作为客户端向代理器订阅相关主题
      mqtt.subscribe(topic, { qos: 0 });//订阅topic（'Temp'）即温度主题，
    }

    function onConnectionLost(response) {
      setTimeout(MQTTconnect, reconnectTimeout);
      // $('#status').val("connection lost: " + responseObject.errorMessage + ". Reconnecting");

    }

    var onMessageArrived = (message) => {//收到所订阅类型消息回调函数，即只要有人发布自己所订阅的消息类型就会调用此函数
      var topic = message.destinationName;//message.destinationName为消息类型，自己定义变量去接收并且解析
      var payload = message.payloadString;//message.payloadString为消息数据，

      var stra = String(payload)
      
      stra = stra.slice(0, stra.length - 1)

      payload = stra.split(',')

      var obj = {}
      for ( var i = 0; i < payload.length ; i++ ) {
      	var arr
      	arr = payload[i].split('=')
      	obj[arr[0]] = arr[1]
      }
      console.log(obj)

      if ( obj.tem != 0 && obj.hum != 0 && obj.light != 0 ) {
        this.$store.dispatch('getData', obj)
        axios({
          method: 'get',
          url: `/api/IntelligentAgriculture/receiveDataController/receiveData/${obj.tem}/${obj.hum}/${obj.light}`,
          headers: {'token': localStorage.getItem('token')}
        }).then(res => {
          this.$store.dispatch('getHistory', res.data.data)
          if (res.data.code === 1001) {
            this.$router.push('/login')
          }
        })
      }
    }
    MQTTconnect()
  },
  methods: {
    flagList () {
      this.flag = !this.flag
    },
    tmp (num) {
      this.$router.push('/setup?id=' + num)
    },
    history () {
      this.$router.push('/history')
    },
    caveat () {
      this.$router.push('/caveat')
    }
  }

}
</script>
<style lang="scss" scoped>
  .box {
    display: flex;
    flex-direction: column;
    padding: 0 50px;
    list-style: none;
    header {
      display: flex;
      justify-content: space-between;
      padding: 20px 0 0 0;
      p {
        font-size: 50px;
      }
      .logo {
        position: relative;
        img {
          display: block;
          &:nth-child(2) {
            position: absolute;
            right: 10px;
            top: 25px;
          }
        }
      }
    }
    .content {
      margin-top: 100px;
      .menu {
        display: flex;
        justify-content: space-between;
        ul {
          list-style: none;
          font-size: 34px;
          span {
            font-weight: bolder;
          }
          .menu_two {
            margin-top: 20px;
            border-radius: 20px;
            position:absolute ;
            // display: none;
            width: 220px;
            background-color: rgba(227, 227, 227, 1);
            padding: 20px 0 20px 30px;
            li {
              line-height: 70px;
              border-bottom: 1px solid #cfcece;
            }
          }
        }
        .news {
          img {
            width: 44px;
            height: 44px;
          }
        }
      }
      .content_box {
        ul {
          margin-top: 100px;
          display: flex;
          justify-content: space-between;
          flex-wrap: wrap;
          li {
            list-style: none;
            padding: 0 20px;
            width: 40.5%;
            height: 400px;
            background: #fff;
            margin-bottom: 50px;
            border-radius: 0 150px 0 0;
            div{
              display: flex;
              justify-content: space-between;
              padding: 50px 0;
              font-size: 34px;
              font-weight: bolder;
              img {
                margin: 7px 35px 0 0;
                width: 20px;
                height: 20px;
              }
            }
            p {
              &:nth-of-type(1) {
                font-size: 60px;
                font-weight: bolder;
                margin: 10px 0 30px 0;
              }
            }
          }
        }
      }
    }
  }
</style>
